package com.carltechnology.mahjonggamecaculation.presenter.impl;

import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.Toast;

import com.carltechnology.mahjonggamecaculation.base.MyAbstractSubscriber;
import com.carltechnology.mahjonggamecaculation.base.MyApplication;
import com.carltechnology.mahjonggamecaculation.dao.DataManager;
import com.carltechnology.mahjonggamecaculation.mode.IGameData;
import com.carltechnology.mahjonggamecaculation.mode.impl.GameDataMode;
import com.carltechnology.mahjonggamecaculation.presenter.IMahjongGameInputPresenter;
import com.carltechnology.mahjonggamecaculation.utils.Utils;
import com.carltechnology.mahjonggamecaculation.views.IMahjongGameInputView;
import com.carltechnology.mahjonggamecaculation.views.impl.MahjongGameInputActivity;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * Created by WZTCM on 2016/6/29.
 */
public class MahjongGameInputPresenter implements IMahjongGameInputPresenter {
    private ExamineSubscriber mySubsHolder;
    private IMahjongGameInputView mView;
    private Observable<ZipStruct> observable;

    private MahjongGameInputPresenter(IMahjongGameInputView view) {
        this.mView = view;
        mySubsHolder = new ExamineSubscriber();
        observable=getExamineObservable().join(getPerunitObservable(),
                new Func1<IGameData, Observable<IGameData>>() {
                    @Override
                    public Observable<IGameData> call(IGameData gameData) {
                        return Observable.just(gameData).delay(100, TimeUnit.MILLISECONDS);
                    }
                }, new Func1<Integer, Observable<Integer>>() {
                    @Override
                    public Observable<Integer> call(Integer integer) {
                        return Observable.just(integer).delay(100, TimeUnit.MILLISECONDS);
                    }
                },
                new Func2<IGameData, Integer, ZipStruct>() {
                    @Override
                    public ZipStruct call(IGameData gameData, Integer integer) {
                        // return null;
                        ZipStruct tmp = new ZipStruct();
                        tmp.iGameData = gameData;
                        tmp.perunit = integer;
                        return tmp;
                    }
                });
        //        observable = Observable.(getExamineObservable(), getPerunitObservable(), new Func2<IGameData, Integer, ZipStruct>() {
        //            @Override
        //            public ZipStruct call(IGameData gameData, Integer integer) {
        //                ZipStruct tmp = new ZipStruct();
        //                tmp.iGameData = gameData;
        //                tmp.perunit = integer;
        //                return tmp;
        //            }
        //        }).observeOn(AndroidSchedulers.mainThread());
        observable.subscribe(mySubsHolder);
    }


    @Override
    public int getPerUnit() {
        return 0;
    }

    @Override
    public void examineAndStoreMahjongGameInfo() {
        String[] names = mView.getAllPlayerNames();
        String perUnit = mView.getEditPerUnit();
        mySubsHolder.subsHolder.onNext(Arrays.asList(names));
        mySubsHolder.detailHolder.onNext(perUnit);
    }

    private Observable<IGameData> getExamineObservable() {
        return Observable.create(new Observable.OnSubscribe<List<String>>() {
            @Override
            public void call(Subscriber<? super List<String>> subscriber) {
                mySubsHolder
                        .subsHolder = subscriber;
            }
        })
                .onBackpressureBuffer(Utils.CONSTANT.ONBACKBUFFER_SMALL_SIZE.getConstant())
                .subscribeOn(Schedulers.computation())
                .observeOn(Schedulers.computation())
                .filter(new Func1<List<String>, Boolean>() {
                    @Override
                    public Boolean call(List<String> list) {
                        for (String tmp : list) {
                            if (!Utils.getInstance().checkNameChese(tmp)) {
                                mView.getHandler().post(new Runnable() {
                                    @Override
                                    public void run() {

                                        Snackbar.make(mView.getContainer(),
                                                MahjongGameInputActivity.MSG_TYPE.CHINESE_ONLY.toString(), Snackbar.LENGTH_SHORT)
                                                .setAction("Undo", new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {

                                                    }
                                                })
                                                .show();
                                    }
                                });
                                return false;
                            }
                        }
                        return true;
                    }
                })
                .map(new Func1<List<String>, IGameData>() {
                    @Override
                    public IGameData call(List<String> list) {
                        return GameDataMode._of((String[]) list.toArray());
                    }
                })
                .filter(new Func1<IGameData, Boolean>() {
                    @Override
                    public Boolean call(IGameData gameData) {
                        String[] names = gameData.getValues();
                        MahjongGameInputActivity.MSG_TYPE resObj = null;
                        if (Utils.getInstance().stringIsEmpty(names[0])) {
                            resObj = MahjongGameInputActivity.MSG_TYPE.PLAYER1_UNCORRECT;
                        } else if (Utils.getInstance().stringIsEmpty(names[1])) {
                            resObj = MahjongGameInputActivity.MSG_TYPE.PLAYER2_UNCORRECT;
                        } else if (Utils.getInstance().stringIsEmpty(names[2])) {
                            resObj = MahjongGameInputActivity.MSG_TYPE.PLAYER3_UNCORRECT;
                        } else if (Utils.getInstance().stringIsEmpty(names[3])) {
                            resObj = MahjongGameInputActivity.MSG_TYPE.PLAYER4_UNCORRECT;
                        }
                        if (resObj != null) {
                            final String res = resObj.toString();
                            mView.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Snackbar.make(mView.getContainer(), res, Snackbar.LENGTH_SHORT)
                                            .setAction("Undo", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            })
                                            .show();
                                }
                            });
                            return false;
                        }
                        return true;
                    }
                }).filter(new Func1<IGameData, Boolean>() {
                    @Override
                    public Boolean call(IGameData gameData) {
                        boolean bRes = MyApplication.getPool().checkId(gameData.getId());
                        if (bRes) {
                            mView.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Snackbar.make(mView.getContainer(), MahjongGameInputActivity.MSG_TYPE.PLAYERS_REPEAT.toString(),
                                            Snackbar.LENGTH_SHORT)
                                            .setAction("Undo", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            })
                                            .show();
                                }
                            });
                            return false;
                        }
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread());
    }

    private Observable<Integer> getPerunitObservable() {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                mySubsHolder
                        .detailHolder = subscriber;
            }
        })
                .onBackpressureBuffer(Utils.CONSTANT.ONBACKBUFFER_SMALL_SIZE.getConstant())
                .subscribeOn(Schedulers.computation())
                .observeOn(Schedulers.computation())
                .filter(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String s) {
                        if (Utils.getInstance().stringIsEmpty(s)) {
                            mView.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Snackbar.make(mView.getContainer(),
                                            MahjongGameInputActivity.MSG_TYPE.PERUNIT_UNCORRECT.toString(),
                                            Snackbar.LENGTH_SHORT)
                                            .setAction("Undo", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            })
                                            .show();
                                }
                            });
                            return false;

                        }
                        return true;
                    }
                })
                .map(new Func1<String, Integer>() {
                    @Override
                    public Integer call(String s) {
                        return Integer.parseInt(s);
                    }
                })
                .filter(new Func1<Integer, Boolean>() {
                    @Override
                    public Boolean call(Integer integer) {
                        boolean bRes = integer <= 0;
                        if (bRes) {
                            mView.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Snackbar.make(mView.getContainer(),
                                            MahjongGameInputActivity.MSG_TYPE.PERUNIT_UNCORRECT.toString(),
                                            Snackbar.LENGTH_SHORT)
                                            .setAction("Undo", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            })
                                            .show();
                                }
                            });
                            return false;
                        }
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread());
    }

    private class ExamineSubscriber extends MyAbstractSubscriber<ZipStruct> {
        Subscriber<? super List<String>> subsHolder;
        Subscriber<? super String> detailHolder;

        @Override
        public void onCompleted() {
            super.onCompleted();
        }

        @Override
        public void onNext(ZipStruct zipStruct) {
            Toast.makeText(mView.getContainer().getContext(), "good", Toast.LENGTH_SHORT).show();
            MyApplication.getPool().setPerUnit(zipStruct.perunit);
            DataManager.getInstance().getInsertHelper()
                    .insertMahjongGameData(new InsertSubscriber(), zipStruct.iGameData);
        }
    }

    private class InsertSubscriber extends MyAbstractSubscriber<IGameData> {

        @Override
        public void onNext(IGameData gameData) {
            MyApplication.getPool().setGameMode(gameData);
            mView.toRunningActivity();
            onCompleted();
        }
    }

    private class ZipStruct {
        IGameData iGameData;
        int perunit;
    }

    public static IMahjongGameInputPresenter newInstance(IMahjongGameInputView vew) {
        return new MahjongGameInputPresenter(vew);

    }
}
